package org.linlinjava.litemall.mechanismadmin.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import org.linlinjava.litemall.core.alipay.config.AliPayProperties;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.ParseXmlUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.mechanismadmin.config.AlipayConfig;
import org.linlinjava.litemall.mechanismadmin.config.Configure;
import org.linlinjava.litemall.mechanismadmin.util.Signature;
import org.linlinjava.litemall.mechanismadmin.util.Util;
import org.linlinjava.litemall.mechanismadmin.util.WxPlaceOrder;
import org.linlinjava.litemall.mechanismadmin.util.XMLParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.alipay.demo.trade.config.Constants.SUCCESS;

@RestController
@RequestMapping("/mechanismadmin/mobilePay")
public class MechanismMobilePayController {

    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private LitemallMechanismService mechanismService;
    @Autowired
    private LitemallMechanismUserService mechanismUserService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private AliPayProperties aliPayProperties;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private LitemallConfigService configService;
    @Autowired
    private LitemallWalletRecordService recordService;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private LitemallWalletRecordService walletRecordService;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private AlipayTradeService alipayTradeService;
    /* *
     * 功能：支付宝手机网站支付接口(alipay.trade.wap.pay)接口调试入口页面
     * 版本：2.0
     * 修改日期：2016-11-01
     * 说明：
     * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
       请确保项目文件有可写权限，不然打印不了日志。
    */
    @GetMapping("/AliPay")
    public Object AliPay(
            String WIDout_trade_no, String WIDsubject, String WIDtotal_amount, String WIDbody) throws UnsupportedEncodingException {
        if (WIDout_trade_no != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = WIDout_trade_no;
            // 订单名称，必填
            String subject = WIDsubject;
            System.out.println(subject);
            // 付款金额，必填
            String total_amount = WIDtotal_amount;
            // 商品描述，可空
            String body = WIDbody;
            // 超时时间 可空
            String timeout_express = "2m";
            // 销售产品码 必填
            String product_code = "QUICK_WAP_WAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);

            // form表单生产
            String form = "";
            Map<String, Object> data = new HashMap<>();
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_request).getBody();
//                response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
//                response.getWriter().write(form);//直接将完整的表单html输出到页面
//                response.getWriter().flush();
//                response.getWriter().close();
            } catch (AlipayApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            data.put("form", form);
            return ResponseUtil.ok(data);
        }

        return ResponseUtil.ok();
    }

    @GetMapping("/queryConfig")
    public Object queryConfig() {
        LitemallConfig integralToANBConfig = configService.findById(10000002);
        Double integralToANBValue = Double.parseDouble(integralToANBConfig.getValue());
        Map<String, Object> data = new HashMap<>();
        data.put("queryConfig", integralToANBValue);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/addWallet")
    public Object addWallet(
            Integer adminId, Integer mechanismId, Integer integral,BigDecimal amount, String mobile, String reason, Byte payType, Byte types, String recordSn) {

        LitemallWalletRecord walletRecords = recordService.queryByRecordSn(recordSn);
        if(walletRecords !=null){
            String  payid =   walletRecords.getPayId();
            if(payid != null || payid.equals("")){
                return ResponseUtil.fail(-1,"该订单已经支付。");
            }
        }

        LitemallUser user = userService.findByMobile(mobile);
        LitemallWalletRecord walletRecord = new LitemallWalletRecord();


        if(integral != null){
            int modifyIntegral = integral;//充值的积分
//        LitemallMechanismUser  litemallMechanismUser =   mechanismUserService.findById(adminId);
            LitemallMechanism mechanism = mechanismService.findById(mechanismId);
            Long integralUsed = mechanism.getIntegralAmountUsed();
            Long integralAll = mechanism.getIntegralAmountAll();
            // 实时根据积分与爱币的比值计算爱币的值
            LitemallConfig integralToANBConfig = configService.findById(10000002);
            Double integralToANBValue = Double.parseDouble(integralToANBConfig.getValue());
            if (integralUsed >= integralAll) {
                integralToANBValue = integralToANBValue + 0.01;
            }
            LitemallConfig ANBToRMBConfig = configService.findById(10000001);
            Double ANBToRMBValue = Double.parseDouble(ANBToRMBConfig.getValue());

            BigDecimal anb = new BigDecimal(integralToANBValue).multiply(new BigDecimal(modifyIntegral)).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal rmb = new BigDecimal(ANBToRMBValue).multiply(anb).setScale(2, BigDecimal.ROUND_HALF_UP);
            if (rmb.compareTo(new BigDecimal(0.01)) < 0) {
                //不足1分按1分计算
                rmb = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            // 开启事务管理
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);
            WxPayUnifiedOrderResult result = null;

            try {
                //1、添加用户充值记录
                //walletRecord.setPayTime(LocalDateTime.now());
                walletRecord.setModifyTime(LocalDateTime.now());
                walletRecord.setActualPayment(rmb);
                walletRecord.setUserId(user.getId());
                walletRecord.setType(types);
                walletRecord.setPayType(payType);
                walletRecord.setModifyResource(mechanismId);
                walletRecord.setRecordSn(recordSn);
                walletRecord.setModifyReason(reason);
                walletRecord.setModifyIntegral(integral);
                recordService.add(walletRecord);
            } catch (Exception ex) {
                txManager.rollback(status);
            }
            txManager.commit(status);
        }else{
            walletRecord.setModifyAmount(amount);
            //walletRecord.setPayTime(LocalDateTime.now());
            walletRecord.setModifyTime(LocalDateTime.now());
            walletRecord.setActualPayment(amount);
            walletRecord.setId(user.getId());
            walletRecord.setType(types);
            walletRecord.setPayType(payType);
            walletRecord.setModifyResource(mechanismId);
            walletRecord.setRecordSn(recordSn);
            walletRecord.setModifyReason(reason);
            recordService.add(walletRecord);
        }

        return ResponseUtil.ok();
    }


    /**
     * @param request 订单号 totalFee 金额 以分单位
     * @return
     * @throws IllegalAccessException
     */
    @GetMapping("/wxpay")
    public Map<String, Object> pay(HttpServletRequest request,
                                   String orderNumber, String openid,Integer money) {

        Map<String, Object> map = new ConcurrentHashMap<String, Object>();
        Map<String, Object> returnMap = new ConcurrentHashMap<String, Object>();
//        int totalPrice = money * 100;
        String prepay_id = "";
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        wxPlaceOrder.setAppid(Configure.APP_ID);
        wxPlaceOrder.setBody("购买商品");
        wxPlaceOrder.setMch_id(Configure.PAY_ID);
        wxPlaceOrder.setNonce_str(Util.uuid());
        wxPlaceOrder.setNotify_url(Configure.NOTIFY_URL);
        wxPlaceOrder.setOpenid(openid);
        wxPlaceOrder.setOut_trade_no(orderNumber);
        wxPlaceOrder.setSpbill_create_ip("127.0.0.1");
		wxPlaceOrder.setTotal_fee(money);
//        wxPlaceOrder.setTotal_fee(1);
        wxPlaceOrder.setTrade_type("JSAPI");
        wxPlaceOrder.setSign(Signature.getSign(wxPlaceOrder));
        XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
        xStream.alias("xml", WxPlaceOrder.class);
        String xml = xStream.toXML(wxPlaceOrder);
        String result = CommondUtil.httpsRequest(Configure.WX_PlACE_ORDER,
                "GET", xml);
        returnMap.put("code", "-1");// 下单失败
        if (!"".equals(result)) {
            try {
                map = XMLParser.getMapFromXML(result);
                if (map.containsKey("prepay_id")) {
                    // 统一下单接口成功
                    prepay_id = "";
                    prepay_id = (String) map.get("prepay_id");
                    // 签名 并返回前端
                    wxPlaceOrder = new WxPlaceOrder();
                    wxPlaceOrder.setAppid(Configure.APP_ID);
                    wxPlaceOrder.setNonce_str(Util.uuid());
                    wxPlaceOrder.setTimeStamp(System.currentTimeMillis() / 1000
                            + "");
                    wxPlaceOrder.setPrepay_id(prepay_id);

                    returnMap.put("nonce_str", wxPlaceOrder.getNonce_str());
                    returnMap.put("appid", Configure.APP_ID);
                    returnMap.put("timeStamp", wxPlaceOrder.getTimeStamp());
                    returnMap
                            .put("paySign", Signature.getSignPay(wxPlaceOrder));
                    returnMap.put("prepay_id", prepay_id);
                    returnMap.put("code", "1");// 下单成功
                }
            } catch (Exception e) {

            }
        }

        return returnMap;
    }

    /**
     * method: checkChargeStatus
     *
     * @Description:检查充值支付结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/17 22:44
     */
    @GetMapping("/checkWxstatus")
    public void checkWxstatus( String orderSn, HttpServletRequest request,HttpServletResponse response) throws Exception {
        Map<String, String> map = ParseXmlUtil.parseXml(request);
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        // 当前订单的通知业务
        if ("SUCCESS".equals(map.get("return_code"))) {
            if ("SUCCESS".equals(map.get("result_code"))) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = map.get("transaction_id");
                // 支付交易成功
                LitemallWalletRecord litemallWalletRecord = walletRecordService.queryByRecordSn(out_trade_no);
                litemallWalletRecord.setPayId(trade_no);
                litemallWalletRecord.setPayTime(LocalDateTime.now());
                walletRecordService.update(litemallWalletRecord);
                //根据类型修改积分还是修改订单状态
                if(litemallWalletRecord.getType() == 1){
                    LitemallUser user =     userService.findById(litemallWalletRecord.getUserId());
                    user.setIntegral(litemallWalletRecord.getModifyIntegral()+user.getIntegral());
                    userService.update(user);

                }
                if(litemallWalletRecord.getType() == 6){
                    LitemallOrder  order  =      litemallOrderService.queryByOrderSn(out_trade_no);
                    order.setPayId(trade_no);
                    order.setOrderStatus(OrderUtil.STATUS_PAY);
                    litemallOrderService.update(order);
                }

            }
            // 通知成功
            wxPlaceOrder.setReturn_code("SUCCESS");
            XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
            xStream.alias("xml", WxPlaceOrder.class);
            String returnXml = xStream.toXML(wxPlaceOrder);
            try {
                response.getWriter().write(returnXml);
            } catch (IOException e) {

            }
        }
    }

    /**
     * method: checkChargeStatus
     * @Description:检查充值支付结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/17 22:44
     */
    @PostMapping("/checkalipaystatus")
    public String  checkAliPayStatus( String orderSn,HttpServletRequest request) {
        Map<String, Object> data = new HashMap<>();
        try {
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            LitemallWalletRecord litemallWalletRecord = walletRecordService.queryByRecordSn(out_trade_no);
            if(trade_no !=null && trade_no != "" && litemallWalletRecord!=null ) {
                if (!trade_no.equals(litemallWalletRecord.getPayId())) {
                    litemallWalletRecord.setPayId(trade_no);
                    litemallWalletRecord.setPayTime(LocalDateTime.now());
                    walletRecordService.update(litemallWalletRecord);
                    LitemallMechanism mechanism = mechanismService.findById(litemallWalletRecord.getModifyResource());
                    //根据类型修改积分还是修改订单状态
                    if (litemallWalletRecord.getType() == 1) {
                        LitemallUser user = userService.findById(litemallWalletRecord.getUserId());
                        user.setIntegral(litemallWalletRecord.getModifyIntegral() + user.getIntegral());
                        userService.update(user);
                        if (user.getMobile() != null && !user.getMobile().equals("")) {
                            String params =
                                    new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + litemallWalletRecord.getModifyIntegral() + "\"}");
                            notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                        }
                    }
                    if (litemallWalletRecord.getType() == 6) {
                        LitemallOrder order = litemallOrderService.queryByOrderSn(out_trade_no);
                        order.setPayId(trade_no);
                        order.setOrderStatus(OrderUtil.STATUS_PAY);
                        litemallOrderService.update(order);
                    }

                }
                return  SUCCESS;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return  "failure";
        }
        return "";
    }

    @RequestMapping("/notify")
    public void notity(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        Map<String, String> map = ParseXmlUtil.parseXml(request);
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        // 当前订单的通知业务
        if ("SUCCESS".equals(map.get("return_code"))) {
            if ("SUCCESS".equals(map.get("result_code"))) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = map.get("transaction_id");
                // 支付交易成功
                LitemallWalletRecord litemallWalletRecord = walletRecordService.queryByRecordSn(out_trade_no);
                if(trade_no !=null && trade_no != "" && litemallWalletRecord!=null){
                if(!trade_no.equals(litemallWalletRecord.getPayId())) {
                    litemallWalletRecord.setPayId(trade_no);
                    litemallWalletRecord.setPayTime(LocalDateTime.now());
                    walletRecordService.update(litemallWalletRecord);
                    LitemallMechanism mechanism = mechanismService.findById(litemallWalletRecord.getModifyResource());
                    //根据类型修改积分还是修改订单状态
                    if (litemallWalletRecord.getType() == 1) {
                        LitemallUser user = userService.findById(litemallWalletRecord.getUserId());
                        user.setIntegral(litemallWalletRecord.getModifyIntegral() + user.getIntegral());
                        userService.update(user);
                        if (user.getMobile() != null && !user.getMobile().equals("")) {
                            String params =
                                    new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + litemallWalletRecord.getModifyIntegral() + "\"}");
                            notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                        }
                    }
                    if (litemallWalletRecord.getType() == 5) {
                        LitemallOrder order = litemallOrderService.queryByOrderSn(out_trade_no);
                        order.setPayId(trade_no);
                        order.setOrderStatus(OrderUtil.STATUS_PAY);
                        litemallOrderService.update(order);
                    }
                }
                }
            }
            // 通知成功
            wxPlaceOrder.setReturn_code("SUCCESS");
            XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
            xStream.alias("xml", WxPlaceOrder.class);
            String returnXml = xStream.toXML(wxPlaceOrder);
            try {
                response.getWriter().write(returnXml);
            } catch (IOException e) {
//                                logError("通知回调 微信服务器 异常", e);
                System.out.println("通知回调 微信服务器 异常:"+ e);
            }


        }

    }




    @GetMapping("/aliPayReturn")
    public Object checkAliPayStatus(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
                //商户订单号

            } catch (UnsupportedEncodingException e) {

            }
        }
        return ResponseUtil.ok(params);
    }


        public static class CommondUtil {
        private static Logger log = LoggerFactory.getLogger(CommondUtil.class);

        public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
            //JSONObject jsonObject = null;
            StringBuffer buffer = null;
            try {
                // 创建SSLContext对象，并使用我们指定的信任管理器初始化
                //TrustManager[] tm = { new MyX509TrustManager() };
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, null, new java.security.SecureRandom());
                // 从上述SSLContext对象中得到SSLSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                URL url = new URL(requestUrl);
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setSSLSocketFactory(ssf);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                // 设置请求方式（GET/POST）
                conn.setRequestMethod(requestMethod);
                //conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                // 当outputStr不为null时向输出流写数据
                if (null != outputStr) {
                    OutputStream outputStream = conn.getOutputStream();
                    // 注意编码格式
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
                }
                // 从输入流读取返回内容
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                // 释放资源
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                inputStream = null;
                conn.disconnect();
                //jsonObject = new JSONObject(buffer.toString());
            } catch (ConnectException ce) {
                log.error("连接服务器错误:" + ce.getMessage());
            } catch (Exception e) {
                log.error("创建ssl失败:" + e.getMessage());
            }
            return buffer.toString();
        }
    }

    @GetMapping("aiBiRecharge")//爱币充值
    public Object payWalletMember(String mobile, Integer integral, String reason, Byte payType, Byte type, Integer mechanismId, Integer adminId) throws Exception {
        LitemallMechanismUser mechanismUser = mechanismUserService.findById(adminId);
        LitemallMechanism mechanism = mechanismService.findById(mechanismId);
        LitemallUser user = userService.findByMobile(mobile);
        if(user == null){
            return ResponseUtil.fail(-3, "没有这个用户");
        }

        if(mechanism.getIntegralAmountUsed() == null){
            mechanism.setIntegralAmountUsed(0L);
        }


        LitemallConfig integralToANBConfig = configService.findById(10000002);
        Double integralToANBValue = Double.parseDouble(integralToANBConfig.getValue());
        Double money = integral * integralToANBValue;
        if(mechanism.getIntegralAmountAll() < integral){
            money = mechanism.getIntegralAmountAll() * integralToANBValue +
                (integral - mechanism.getIntegralAmountAll()) * integralToANBValue +
                (integral - mechanism.getIntegralAmountAll()) * integralToANBValue * 0.01;
        }

        if(mechanismUser.getBalance() == null){
            mechanismUser.setBalance( new BigDecimal(0));
        }

        if(mechanismUser.getBalance().doubleValue() < money){
            return ResponseUtil.fail(-2, "您的爱币不足");
        }

        if(user.getIntegral() == null){
            user.setIntegral(0);
        }
        user.setIntegral(user.getIntegral()+integral);
        Double balance = mechanismUser.getBalance().doubleValue() - money;
        BigDecimal bd = new BigDecimal(balance);
        mechanismUser.setBalance(bd);

        LitemallWalletRecord walletRecordMechanism  = new LitemallWalletRecord();

        walletRecordMechanism.setType(type);
        walletRecordMechanism.setPayType(payType);
        walletRecordMechanism.setModifyReason(reason);
        String recordSn = litemallOrderService.generateOrderSn(adminId);
        walletRecordMechanism.setRecordSn(recordSn);
        BigDecimal modifyAmountMechanism =  new BigDecimal(money);

        walletRecordMechanism.setModifyAmount(modifyAmountMechanism);

        walletRecordMechanism.setUserId(user.getId());

        walletRecordMechanism.setModifyReason(reason);
        walletRecordMechanism.setModifyTime(LocalDateTime.now());
        walletRecordMechanism.setModifyResource(mechanismId);

        userService.update(user);
        mechanismUserService.update(mechanismUser);
        walletRecordService.add(walletRecordMechanism);

        if (user.getMobile() != null && !user.getMobile().equals("")) {
            String params =
                    new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + walletRecordMechanism.getModifyIntegral() + "\"}");
            notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
        }
        //扣除机构额度
        mechanism.setIntegralAmountUsed(mechanism.getIntegralAmountUsed() + integral);
        if(mechanism.getIntegralAmountAll() >= integral) {
            mechanism.setIntegralAmountAll(mechanism.getIntegralAmountAll() - integral);
        }else{
            mechanism.setIntegralAmountAll(0L);
        }
        mechanismService.updateById(mechanism);

        Integer walletRecordId =walletRecordMechanism.getId();
        if(walletRecordId == null || walletRecordId.equals("") ){
            return ResponseUtil.fail(-1, "支付失败");
        }
        return ResponseUtil.ok("success");
    }
}